package com.wl.shixun3.controller;

import com.wl.shixun3.entity.User;
import com.wl.shixun3.service.UserService;
import com.wl.shixun4.util.SessionManager;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 登录控制器
 */
@WebServlet("/shixun3/login")
public class LoginController extends HttpServlet {
    private UserService userService;

    @Override
    public void init() throws ServletException {
        userService = new UserService();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 转发到登录页面
        request.getRequestDispatcher("/shixun3/login.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");

        // 获取表单参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 参数验证
        if (username == null || username.trim().isEmpty() || 
            password == null || password.trim().isEmpty()) {
            request.setAttribute("errorMessage", "用户名和密码不能为空！");
            request.getRequestDispatcher("/shixun3/login.jsp").forward(request, response);
            return;
        }

        // 检查用户是否已经在其他设备登录
        if (SessionManager.isUserLoggedIn(username)) {
            request.setAttribute("errorMessage", "该账号已在其他设备登录，请先退出后再登录！");
            request.getRequestDispatcher("/shixun3/login.jsp").forward(request, response);
            return;
        }

        // 验证用户凭据
        User user = userService.login(username, password);
        
        if (user != null) {
            // 登录成功，创建会话
            HttpSession session = request.getSession(true);
            session.setAttribute("user", user);
            session.setAttribute("username", username);
            session.setAttribute("isAuthenticated", true);
            
            // 记录登录时间
            String loginTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            session.setAttribute("loginTime", loginTime);
            
            // 设置会话超时时间（30分钟）
            session.setMaxInactiveInterval(30 * 60);
            
            // 将会话添加到SessionManager
            SessionManager.addSession(username, session);
            
            // 重定向到成功页面
            response.sendRedirect(request.getContextPath() + "/shixun3/success.jsp");
        } else {
            // 登录失败
            request.setAttribute("errorMessage", "用户名或密码错误！");
            request.getRequestDispatcher("/shixun3/login.jsp").forward(request, response);
        }
    }
}

